import csv
import math
def pre1(name):
    reader = open('./data/'+name+'.txt')
    list_data = reader.readlines()
    #n代表一行数据的个数
    n=len(list_data[0].replace("\n",'').replace(",",'').split(' '))
    columns=[]
    for i in range(n-1):
        columns.append('因子'+str(i+1))
    columns.append('决策属性')
    data=[]
    for i in list_data:
        data.append(i.replace("\n",'').split(','))
    for i in range(len(data)):
       data[i]=list(map(float,data[i]))
    #print(data)
    #连续离散化 disperse
    '''
    for i1 in range(n - 1):
        x1 = []
        y = []
        for row in data:
            x1.append(row[i1])
            y.append(row[n - 1])
        val=[]
        for i in x1:
            x = []
            for j in range(len(x1)):
                if x1[j] >= i:
                    x.append(1)
                else:
                    x.append(-1)

            x_cnt = {}  # 将结果用一个字典存储
            y_cnt = {}  # 将结果用一个字典存储
            # 统计结果
            for value in y:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                y_cnt[value] = y_cnt.get(value, 0) + 1
            y_key = [key for key in y_cnt.keys()]
            y_value = [value for value in y_cnt.values()]
            for value in x:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                x_cnt[value] = x_cnt.get(value, 0) + 1
            x_key = [key for key in x_cnt.keys()]
            x_value = [value for value in x_cnt.values()]
            # print(x_cnt)
            info_x0 = []
            info_x = 0
            for k in range(len(x_key)):
                x0_cnt = {}
                info_x0.append(0)
                # print("计算",lables[i], ":",x_key[k],"的条件熵")
                for l in y_key:
                    for j in range(len(x)):
                        if x[j] == x_key[k] and y[j] == l:
                            x0_cnt[l] = x0_cnt.get(l, 0) + 1
                #print(x0_cnt)
                for v in x0_cnt.values():
                    info_x0[k] = info_x0[k] - v / x_value[k] * math.log(v / x_value[k]) / math.log(2)
                info_x = info_x + x_value[k] / len(x) * info_x0[k]
            val.append(info_x)
        #print(val)
        ind=val.index(min(val))
        #print(min(val))
        maxi=x1[ind]
        #print(maxi)
        for d in data:
            if d[i1] >= maxi:
                d[i1] = 1
            else :
                d[i1] = -1
    '''
    with open('./data1/'+name+".csv", "w", encoding='utf-8', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 先写入columns_name
        writer.writerow(columns)
        # 写入多行用writerows
        writer.writerows(data)
    print(name,"离散化完成！")
def pre2(name):
    reader = open('./data/'+name+'.txt')
    list_data = reader.readlines()
    #n代表一行数据的个数
    n=len(list_data[0].replace("\n",'').split(','))
    columns=[]
    for i in range(n-1):
        columns.append('因子'+str(i+1))
    columns.append('决策属性')
    data=[]
    for i in list_data:
        data.append(i.replace("\n",'').split(','))
    for i in range(len(data)):
        try:
           data[i]=list(map(float,data[i]))
        except:
            print(data[i])
    #print(data)
    #连续离散化 disperse
    '''
    for i1 in range(n - 1):
        x1 = []
        y = []
        for row in data:
            x1.append(row[i1])
            y.append(row[n - 1])
        val=[]
        for i in x1:
            x = []
            for j in range(len(x1)):
                if x1[j] >= i:
                    x.append(1)
                else:
                    x.append(-1)

            x_cnt = {}  # 将结果用一个字典存储
            y_cnt = {}  # 将结果用一个字典存储
            # 统计结果
            for value in y:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                y_cnt[value] = y_cnt.get(value, 0) + 1
            y_key = [key for key in y_cnt.keys()]
            y_value = [value for value in y_cnt.values()]
            for value in x:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                x_cnt[value] = x_cnt.get(value, 0) + 1
            x_key = [key for key in x_cnt.keys()]
            x_value = [value for value in x_cnt.values()]
            # print(x_cnt)
            info_x0 = []
            info_x = 0
            for k in range(len(x_key)):
                x0_cnt = {}
                info_x0.append(0)
                # print("计算",lables[i], ":",x_key[k],"的条件熵")
                for l in y_key:
                    for j in range(len(x)):
                        if x[j] == x_key[k] and y[j] == l:
                            x0_cnt[l] = x0_cnt.get(l, 0) + 1
                #print(x0_cnt)
                for v in x0_cnt.values():
                    info_x0[k] = info_x0[k] - v / x_value[k] * math.log(v / x_value[k]) / math.log(2)
                info_x = info_x + x_value[k] / len(x) * info_x0[k]
            val.append(info_x)
        #print(val)
        ind=val.index(min(val))
        #print(min(val))
        maxi=x1[ind]
        #print(maxi)
        for d in data:
            if d[i1] >= maxi:
                d[i1] = 1
            else :
                d[i1] = -1
    '''
    with open('./data1/'+name+".csv", "w", encoding='utf-8', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 先写入columns_name
        writer.writerow(columns)
        # 写入多行用writerows
        writer.writerows(data)
    print(name,"离散化完成！")
def pre3(name):
    reader = open('./data/'+name+'.txt')
    list_data = reader.readlines()
    #n代表一行数据的个数
    n=len(list_data[0].replace("\n",'').split(' '))
    columns=[]
    for i in range(n-1):
        columns.append('因子'+str(i+1))
    columns.append('决策属性')
    data=[]
    for i in list_data:
        data.append(i.replace("\n",'').split(' '))
    for i in range(len(data)):
       data[i]=list(map(float,data[i]))
    #print(data)
    #连续离散化 disperse
    '''
    for i1 in range(n - 1):
        x1 = []
        y = []
        for row in data:
            x1.append(row[i1])
            y.append(row[n - 1])
        val=[]
        for i in x1:
            x = []
            for j in range(len(x1)):
                if x1[j] >= i:
                    x.append(1)
                else:
                    x.append(-1)

            x_cnt = {}  # 将结果用一个字典存储
            y_cnt = {}  # 将结果用一个字典存储
            # 统计结果
            for value in y:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                y_cnt[value] = y_cnt.get(value, 0) + 1
            y_key = [key for key in y_cnt.keys()]
            y_value = [value for value in y_cnt.values()]
            for value in x:
                # get(value, num)函数的作用是获取字典中value对应的键值, num=0指示初始值大小。
                x_cnt[value] = x_cnt.get(value, 0) + 1
            x_key = [key for key in x_cnt.keys()]
            x_value = [value for value in x_cnt.values()]
            # print(x_cnt)
            info_x0 = []
            info_x = 0
            for k in range(len(x_key)):
                x0_cnt = {}
                info_x0.append(0)
                # print("计算",lables[i], ":",x_key[k],"的条件熵")
                for l in y_key:
                    for j in range(len(x)):
                        if x[j] == x_key[k] and y[j] == l:
                            x0_cnt[l] = x0_cnt.get(l, 0) + 1
                #print(x0_cnt)
                for v in x0_cnt.values():
                    info_x0[k] = info_x0[k] - v / x_value[k] * math.log(v / x_value[k]) / math.log(2)
                info_x = info_x + x_value[k] / len(x) * info_x0[k]
            val.append(info_x)
        #print(val)
        ind=val.index(min(val))
        #print(min(val))
        maxi=x1[ind]
        #print(maxi)
        for d in data:
            if d[i1] >= maxi:
                d[i1] = 1
            else :
                d[i1] = -1
    '''
    with open('./data1/'+name+".csv", "w", encoding='utf-8', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 先写入columns_name
        writer.writerow(columns)
        # 写入多行用writerows
        writer.writerows(data)
    print(name,"离散化完成！")
if __name__=='__main__':
    names1 = ['iris', 'glasss'] #以 ', '分割
    for name in names1:
        # pre.pre(name)
        pre1(name)
    names2=['liver','cleveland'] #以 ','分割
    for name in names2:
        # pre.pre(name)
        pre2(name)
    names3=['heart'] #以 ' '分割
    for name in names3:
        # pre.pre(name)
        pre3(name)

